<template>
  <div class="article-detail-page" v-if="article.id">
    <nav class="nav">
      <span @click="$router.back()" class="back">&lt;</span> 面经详情
    </nav>
    <header class="header">
      <h1>{{ article.stem }}</h1>
      <p>{{ formatDateTime(article.createdAt) }} | 浏览量 {{ article.views }} | 点赞数 {{ article.likeCount }} | 评论数 {{ article.commentCount }}</p>
      <p>
        <img :src="getCreatorAvatarUrl(article.creatorAvatar)" alt="">
        <span>{{ article.creatorName }}</span>
      </p>
    </header>
    <main class="body">
      {{ article.content }}
    </main>
    <section class="comments-section">
      <div class="comments-header">
        <h2>评论</h2>
        <button class="add-comment-button" @click="toggleAddCommentForm">新增评论</button>
      </div>
      <ul class="comments-list" v-if="!showAddCommentForm">
        <li v-for="comment in comments" :key="comment.id" class="comment-item">
          <img :src="getCreatorAvatarUrl(comment.userAvatar)" alt="" class="comment-avatar">
          <div class="comment-details">
            <p class="comment-nickname">{{ comment.userNickname }}</p>
            <p class="comment-content">{{ comment.content }}</p>
            <p class="comment-created-at">{{ formatDateTime(comment.createdAt) }}</p>
            <p class="comment-like-count">点赞数: {{ comment.likeCount }}</p>
          </div>
        </li>
      </ul>
      <form v-if="showAddCommentForm" @submit.prevent="submitComment" class="add-comment-form">
        <textarea v-model="newCommentContent" placeholder="请输入评论内容" required></textarea>
        <button type="submit">提交评论</button>
        <button type="button" @click="toggleAddCommentForm">取消</button>
      </form>
    </section>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'ArticleDetailPage',
  data () {
    return {
      user: null,
      article: {},
      comments: [],
      showAddCommentForm: false,
      newCommentContent: ''
    }
  },
  async created () {
    this.fetchUserData();
    const id = this.$route.params.id;
    try {
      // 获取文章详情
      const { data: articleData } = await axios.get(`http://localhost:8000/getArticle/${id}`);
      console.log(articleData); // 检查返回的数据结构
      this.article = articleData; // 假设后端直接返回 Article 对象
      console.log(this.article);

      // 获取评论列表
      const { data: commentsData } = await axios.get(`http://localhost:8000/articles/${id}/comments`);
      console.log(commentsData); // 检查返回的数据结构
      this.comments = commentsData; // 假设后端返回评论数组
      console.log(this.comments);
    } catch (error) {
      console.error('请求失败:', error);
    }
  },
  methods: {
    getCreatorAvatarUrl(avatarPath) {
      if (avatarPath.startsWith('http://localhost:5000/')) {
        avatarPath = avatarPath.replace('http://localhost:5000/', '');
      }
      if (!avatarPath.startsWith('http')) {
        avatarPath = require(`@/assets/upload/${avatarPath}`);
      }
      return avatarPath;
    },

    formatDateTime(datetime) {
      if (!datetime) return '';
      const date = new Date(datetime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    async fetchUserData() {
      try {
        const userId = localStorage.getItem('userId');
        if (!userId) {
          throw new Error('用户ID未找到');
        }

        const response = await axios.get(`http://localhost:8000/getuserbyid?id=${userId}`);
        this.user = response.data;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        alert('获取用户信息失败，请重试。');
      }
    },

    toggleAddCommentForm() {
      this.showAddCommentForm = !this.showAddCommentForm;
      this.newCommentContent = ''; // 清空输入框
    },

    async submitComment() {
      const articleId = this.$route.params.id;
      const newComment = {
        userId: this.user.id,
        userAvatar: this.user.avatar,
        userNickname: this.user.nickname,
        content: this.newCommentContent
      };

      try {
        const response = await axios.post(`http://localhost:8000/articles/${articleId}/comments`, newComment);
        alert('评论提交成功');
        console.log('评论提交成功:', response.data);
        this.comments.push(response.data); // 更新评论列表
        this.toggleAddCommentForm(); // 关闭表单
      } catch (error) {
        console.error('评论提交失败:', error);
        alert('评论提交失败，请重试。');
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-detail-page {
  .nav {
    height: 44px;
    border-bottom: 1px solid #e4e4e4;
    line-height: 44px;
    text-align: center;
    .back {
      font-size: 18px;
      color: #666;
      position: absolute;
      left: 10px;
      top: 0;
      transform: scale(1, 1.5);
    }
  }
  .header {
    padding: 0 15px;
    p {
      color: #999;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }
  .body {
    padding: 0 15px;
  }
  .comments-section {
    margin-top: 20px;
    padding: 0 15px;
    .comments-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      h2 {
        font-size: 18px;
        margin-right: 40px;
      }
      .add-comment-button {
        background-color: whitesmoke;
        color: black;
        border: 1px solid black; /* 添加黑色边框 */
        padding: 5px 10px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 18px;
        font-weight: bold;
      }
    }
    .comments-list {
      list-style: none;
      padding: 0;
      .comment-item {
        display: flex;
        align-items: flex-start;
        margin-bottom: 20px;
        .comment-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          margin-right: 10px;
        }
        .comment-details {
          .comment-nickname {
            font-weight: bold;
            margin-bottom: 5px;
          }
          .comment-content {
            margin-bottom: 5px;
          }
          .comment-created-at {
            color: #999;
            font-size: 12px;
            margin-bottom: 5px;
          }
          .comment-like-count {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
    .add-comment-form {
      margin-top: 20px;
      textarea {
        width: 100%;
        height: 100px;
        padding: 10px;
        box-sizing: border-box;
        border: 1px solid #ccc;
        border-radius: 4px;
        resize: vertical;
      }
      button {
        margin-top: 10px;
        padding: 5px 10px;
        border: 1px solid black;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        background-color: white;
      }
    }
  }
}
</style>